﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace ATM
{
    class ATM
    {
        static void Withdraw(int acountId, double amount, string pin)
        {
            SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;User ID=Ivan;Password=1234");
            conn.Open();
            using (conn)
            {
                SqlTransaction trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);

                SqlCommand cmd = new SqlCommand("select Id from Accounts where Id=@accId and CardPIN=@pin", conn);
                cmd.Parameters.Add("@pin", pin);
                cmd.Parameters.Add("@accId", acountId);

                cmd.Transaction = trans;

                SqlDataReader reader = cmd.ExecuteReader();
                using (reader)
                {
                    if (!reader.HasRows)
                    {
                        Console.WriteLine("Incorrect PIN!");
                        reader.Close();
                        trans.Rollback();
                        return;
                    }
                }

                cmd = new SqlCommand("select Id from Accounts where Id=@accId and CardPIN=@pin and CardCash>=@amount", conn);
                cmd.Parameters.Add("@amount", amount);
                cmd.Parameters.Add("@pin", pin);
                cmd.Parameters.Add("@accId", acountId);

                cmd.Transaction = trans;

                reader = cmd.ExecuteReader();
                using (reader)
                {
                    if (!reader.HasRows)
                    {
                        Console.WriteLine("Insufficient funds!");
                        reader.Close();
                        trans.Rollback();
                        return;
                    }
                }

                cmd = new SqlCommand("update Accounts set CardCash = CardCash - @amount where " +
                    "Id=@accId and CardPIN=@pin and CardCash>=@amount", conn);
                cmd.Parameters.Add("@amount", amount);
                cmd.Parameters.Add("@pin", pin);
                cmd.Parameters.Add("@accId", acountId);
                cmd.Transaction = trans;
                if (cmd.ExecuteNonQuery() > 0)
                {
                    Console.WriteLine("Transaction successful!");
                    trans.Commit();
                }
                else
                {
                    Console.WriteLine("Transaction failed!");
                    trans.Rollback();
                }

            }
        }

        static void Main(string[] args)
        {
            Withdraw(3,222.2,"8521");
        }
    }
}
